<script lang="ts" setup>
import type { BOMApi } from '#/models/bom/bom';

import { computed, nextTick, reactive, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, message, Tabs, TabPane } from 'ant-design-vue';
import { VxeGrid } from 'vxe-table';

import { useVbenForm } from '#/adapter/form';
import { $t } from '#/locales';
import { BOMModel } from '#/models/bom/bom';
import { checkBOMCodeUnique } from '#/api/bom/bom';

import { UNIT_OPTIONS, useSchema, useTabbedSchema } from '../data';
import ComponentSelectModal from './component-select.vue';

const emit = defineEmits(['success']);

const confirmLoading = ref(false);
const activeKey = ref('basic');
const formData = ref<Partial<BOMApi.BOM>>();
const componentSelectVisible = ref(false);
const componentGridRef = ref();
const bomComponents = ref<
  Array<{
    is_optional: boolean;
    is_phantom: boolean;
    material_code: string;
    material_id: number;
    material_name: string;
    position: string;
    quantity: number;
    scrap_rate: number;
    specification: string;
    unit: string;
  }>
>([]);

const formModel = new BOMModel();

// 获取弹窗标题
const getTitle = computed(() => {
  return formData.value?.bom_id
    ? $t('ui.actionTitle.edit', [$t('bom.bom.title')])
    : $t('ui.actionTitle.create', [$t('bom.bom.title')]);
});

// 获取表单配置和选项卡配置
const schema = useSchema();
const tabbedSchema = useTabbedSchema();

// 过滤schema，只显示当前tab下的字段
const filteredSchema = computed(() => {
  const currentTab = tabbedSchema.find(
    (item) => item.key === activeKey.value,
  );
  if (!currentTab) return [];

  return schema.filter((field) => {
    // 确保所有需要显示的字段都能被正确包含
    return currentTab.fields.includes(field.fieldName);
  });
});

// 初始化表单，设置正确的布局和初始配置
const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  showDefaultActions: false,
});

// 监听产品选择变化，自动生成BOM编码
watch(
  async () => {
    try {
      const values = await formApi.getValues();
      return values.product;
    } catch (error) {
      console.error('获取表单值失败:', error);
      return null;
    }
  },
  async (newValue, oldValue) => {
    // 只在新增模式下且产品值发生变化时生成BOM编码
    if (newValue && newValue !== oldValue && !formData.value?.bom_id) {
      try {
        // 获取产品详情
        const productApi = await import('#/api/product/product');
        const product = await productApi.getProduct(Number(newValue));
        
        // 获取当前版本号
        const values = await formApi.getValues();
        const version = values.version || '1.0';
        
        // 生成BOM编码：BOM-{产品SKU}-{版本号}
        const bomCode = `BOM-${product.sku}-${version}`;
        
        // 设置BOM编码
        await formApi.setFieldValue('bom_code', bomCode);
      } catch (error) {
        console.error('获取产品信息失败:', error);
        message.error('获取产品信息失败，请手动输入BOM编码');
      }
    }
  },
);

// 监听版本号变化，更新BOM编码
watch(
  async () => {
    try {
      const values = await formApi.getValues();
      return values.version;
    } catch (error) {
      console.error('获取表单值失败:', error);
      return null;
    }
  },
  async (newValue, oldValue) => {
    // 只在新增模式下且版本号发生变化时更新BOM编码
    if (newValue && newValue !== oldValue && !formData.value?.bom_id) {
      try {
        const values = await formApi.getValues();
        const productId = values.product;
        if (productId) {
          // 获取产品详情
          const productApi = await import('#/api/product/product');
          const product = await productApi.getProduct(Number(productId));
          
          // 生成BOM编码：BOM-{产品SKU}-{版本号}
          const bomCode = `BOM-${product.sku}-${newValue}`;
          
          // 设置BOM编码
          await formApi.setFieldValue('bom_code', bomCode);
        }
      } catch (error) {
        console.error('获取产品信息失败:', error);
      }
    }
  },
);

// 组件表格配置
const componentGridOptions = reactive({
  columns: [
    { type: 'seq' as const, width: 60 },
    { field: 'material_code', title: '物料编码', width: 150 },
    { field: 'material_name', title: '物料名称', width: 200 },
    { field: 'specification', title: '规格型号', width: 200 },
    {
      field: 'quantity',
      title: '数量',
      width: 100,
      editRender: { name: 'input' },
    },
    { 
      field: 'unit', 
      title: '单位', 
      width: 120,
      editRender: { 
        name: '$select',
        options: UNIT_OPTIONS,
        props: {
          placeholder: '请选择单位'
        }
      }
    },
    {
      field: 'position',
      title: '位号',
      width: 120,
      editRender: { name: 'input' },
    },
    {
      field: 'is_phantom',
      title: '虚拟件',
      width: 80,
      editRender: { name: 'switch' },
    },
    {
      field: 'is_optional',
      title: '可选件',
      width: 80,
      editRender: { name: 'switch' },
    },
    {
      field: 'scrap_rate',
      title: '报废率(%)',
      width: 100,
      editRender: { name: 'input' },
    },
    { field: 'action', title: '操作', width: 80 },
  ],
  data: bomComponents.value,
  editConfig: { trigger: 'click' as const, mode: 'cell' as const },
  toolbarConfig: {
    slots: {
      buttons: 'toolbar',
    },
  },
});

/**
 * 重置表单
 */
function resetForm() {
  try {
    formApi.resetForm();
    if (formData.value) {
      formApi.setValues(formData.value);
    }
  } catch (error) {
    console.error('重置表单时出错:', error);
  }
}

// 添加组件
const handleAddComponent = () => {
  componentSelectVisible.value = true;
};

// 导入组件
const handleImportComponents = () => {
  // 实现导入组件逻辑
  message.info('导入组件功能开发中');
};

// 组件选择确认
const handleComponentSelect = (selectedComponents: Array<{
  material_code: string;
  material_id: number | string;
  material_name: string;
  specification: string;
  unit: string}>) => {
  selectedComponents.forEach((component) => {
    // 检查是否已存在
    const exists = bomComponents.value.some(
      (item) => item.material_id === component.material_id,
    );
    if (!exists) {
      bomComponents.value.push({
        material_id: typeof component.material_id === 'string' 
          ? parseInt(component.material_id, 10) 
          : component.material_id,
        material_code: component.material_code,
        material_name: component.material_name,
        specification: component.specification,
        quantity: 1,
        unit: component.unit,
        position: '',
        is_phantom: false,
        is_optional: false,
        scrap_rate: 0,
      });
    }
  });
};

// 移除组件
const handleRemoveComponent = (row: {
  is_optional: boolean;
  is_phantom: boolean;
  material_code: string;
  material_id: number;
  material_name: string;
  position: string;
  quantity: number;
  scrap_rate: number;
  specification: string;
  unit: string;
}) => {
  const index = bomComponents.value.findIndex(
    (item) => item.material_id === row.material_id,
  );
  if (index > -1) {
    bomComponents.value.splice(index, 1);
  }
};

// 创建弹窗实例
const [Modal, modalApi] = useVbenModal({
  // 设置弹窗居中显示
  centered: true,
  /**
   * 表单提交处理
   */
  async onConfirm() {
    // 验证表单
    const { valid } = await formApi.validate();
    if (valid) {
      confirmLoading.value = true; // 设置加载状态
      modalApi.lock(); // 锁定弹窗，防止重复提交
      const data = await formApi.getValues(); // 获取表单数据

      try {
        // 验证组件
        if (
          activeKey.value === 'components' &&
          bomComponents.value.length === 0
        ) {
          message.warning('请至少添加一个组件');
          modalApi.lock(false);
          confirmLoading.value = false; // 重置加载状态
          return;
        }

        // 准备提交数据
        const submitData = {
          ...data,
          // 确保product字段正确映射到product_id
          product_id: data.product,
          bom_code: data.bom_code, // 确保bom_code字段被包含
          components: bomComponents.value,
        };

        // 如果是编辑模式，需要验证BOM编码唯一性
        if (formData.value?.bom_id && submitData.bom_code) {
          try {
            const isUnique = await checkBOMCodeUnique(submitData.bom_code, formData.value.bom_id);
            if (!isUnique) {
              message.error('BOM编码已存在，请使用其他编码');
              modalApi.lock(false);
              confirmLoading.value = false;
              return;
            }
          } catch (error) {
            console.error('验证BOM编码唯一性时出错:', error);
            message.error('验证BOM编码唯一性时出错，请稍后重试');
            modalApi.lock(false);
            confirmLoading.value = false;
            return;
          }
        }

        // 根据是否有id决定是更新还是创建
        try {
          await (formData.value?.bom_id
            ? formModel.update(formData.value.bom_id, submitData)
            : formModel.create(submitData));
          await modalApi.close();
          emit('success');
        } catch (error) {
          console.error('提交表单时出错:', error);

          // 解析错误信息并显示给用户
          if (error && typeof error === 'object') {
            // 检查是否是验证错误
            let errorMessage = '提交失败：\n';

            // 处理不同格式的错误响应
            if ((error as any)?.response?.data) {
              const errorData = (error as any).response?.data;

              // 检查是否是JSON格式的错误
              if (typeof errorData === 'string') {
                try {
                  const parsedError = JSON.parse(errorData);
                  if (parsedError.status) {
                    errorMessage += `BOM状态：${Array.isArray(parsedError.status) ? parsedError.status.join('，') : parsedError.status}\n`;
                  } else {
                    errorMessage += errorData;
                  }
                } catch (e) {
                  // 如果不是JSON格式，直接显示错误信息
                  errorMessage += errorData;
                }
              } else if (
                'status' in errorData ||
                Object.keys(errorData).length > 0
              ) {
                // 处理对象格式的错误
                for (const [field, messages] of Object.entries(errorData)) {
                  const fieldNames: Record<string, string> = {
                    status: 'BOM状态',
                    bom_code: 'BOM编码',
                    bom_name: 'BOM名称',
                    product_id: '产品',
                  };
                  const fieldName = fieldNames[field] || field;
                  errorMessage += `${fieldName}：${Array.isArray(messages) ? messages.join('，') : messages}\n`;
                }
              } else {
                errorMessage += '未知错误';
              }
            } else if (
              'status' in error ||
              'bom_code' in error ||
              Object.keys(error).length > 0
            ) {
              // 原始错误处理逻辑
              for (const [field, messages] of Object.entries(error)) {
                const fieldNames: Record<string, string> = {
                  status: 'BOM状态',
                  bom_code: 'BOM编码',
                  bom_name: 'BOM名称',
                  product_id: '产品',
                };
                const fieldName = fieldNames[field] || field;
                errorMessage += `${fieldName}：${Array.isArray(messages) ? messages.join('，') : messages}\n`;
              }
            } else {
              errorMessage = '提交表单时出现错误，请稍后重试';
            }
            message.error(errorMessage);
          } else {
            message.error('提交表单时出现错误，请稍后重试');
          }
        }
      } finally {
        modalApi.lock(false);
        confirmLoading.value = false; // 重置加载状态
      }
    }
  },
  /**
   * 弹窗打开/关闭时的处理
   * @param isOpen 是否打开
   */
  onOpenChange(isOpen) {
    try {
      // 弹窗打开时，设置表单数据
      if (isOpen) {
        const data = modalApi.getData<BOMApi.BOM>(); // 获取弹窗数据
        if (data) {
          // 更新formData
          formData.value = data;

          // 创建表单值对象，包含必要的字段
          const formValues = { 
            ...data,
            // 确保product字段正确映射
            product: data.product,
          };

          // 重置表单并设置数据
          resetForm();
          nextTick(() => {
            try {
              formApi.setValues(formValues);
            } catch (error) {
              console.error('设置表单值时出错:', error);
            }
          });

          // 加载BOM组件
          if (data.components && data.components.length > 0) {
            bomComponents.value = data.components.map((component) => ({
              material_id: component.material,
              material_code: '', // 需要从后端获取或通过API查询
              material_name: component.material_name || '',
              specification: '', // 需要从后端获取或通过API查询
              quantity: component.quantity,
              unit: component.unit,
              position: '',
              is_phantom: false,
              is_optional: false,
              scrap_rate: component.scrap_rate,
            }));
          } else {
            bomComponents.value = [];
          }
        } else {
          // 新增模式时重置并设置默认值
          formData.value = undefined;

          // 重置表单并设置默认值
          resetForm();
          nextTick(async () => {
            try {
              const defaultValues = {
                bom_code: '',
                bom_name: '',
                product: undefined, // 使用product而不是product_id
                version: '1.0',
                bom_type: 'production',
                status: 'draft',
                lifecycle_status: 'development',
                effective_date: null,
                expiry_date: null,
                remark: '',
              };

              formApi.setValues(defaultValues);
            } catch (error) {
              console.error('设置默认表单值时出错:', error);
            }
          });

          // 重置组件列表
          bomComponents.value = [];
        }
      }
    } catch (error) {
      console.error('处理弹窗打开/关闭事件时出错:', error);
    }
  },
});
</script>

<template>
  <Modal :title="getTitle" :confirm-loading="confirmLoading" class="w-[800px]">
    <div class="form-wrapper">
      <Tabs v-model:activeKey="activeKey" type="line" sticky="top">
        <TabPane key="basic" tab="基础信息">
          <Form :schema="filteredSchema">
            <template #prepend-footer>
              <div class="flex-auto">
                <Button type="primary" danger @click="resetForm">
                  {{ $t('common.reset') }}
                </Button>
              </div>
            </template>
          </Form>
        </TabPane>
        
        <TabPane key="components" tab="BOM组件">
          <div class="space-y-4">
            <VxeGrid ref="componentGridRef" v-bind="componentGridOptions">
              <template #toolbar>
                <Button type="primary" @click="handleAddComponent">
                  添加组件
                </Button>
                <Button @click="handleImportComponents">导入组件</Button>
              </template>

              <template #action="scope">
                <Button danger size="small" @click="handleRemoveComponent(scope.row)">
                  删除
                </Button>
              </template>
            </VxeGrid>
          </div>
        </TabPane>
        
        <TabPane key="alternatives" tab="替代物料">
          <div class="space-y-4">
            <div class="mb-4">
              <Button type="primary">添加替代物料</Button>
            </div>
            <div class="py-8 text-center text-gray-500">
              替代物料功能开发中...
            </div>
          </div>
        </TabPane>
        
        <TabPane key="documents" tab="文档">
          <div class="space-y-4">
            <div class="mb-4">
              <Button type="primary">上传文档</Button>
            </div>
            <div class="py-8 text-center text-gray-500">
              文档管理功能开发中...
            </div>
          </div>
        </TabPane>
        
        <TabPane key="versions" tab="版本历史">
          <div class="space-y-4">
            <div class="py-8 text-center text-gray-500">
              版本历史功能开发中...
            </div>
          </div>
        </TabPane>
      </Tabs>
    </div>

    <ComponentSelectModal
      v-model:visible="componentSelectVisible"
      @confirm="handleComponentSelect"
    />
  </Modal>
</template>

<style lang="css" scoped>
/* 表单包装器 - 全局布局控制 */
.form-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

/* Modal整体布局优化 */
:deep(.ant-modal) {
  width: 1200px !important;
  max-width: 90vw !important;
}

/* 调整Modal内容区域高度，确保有足够的显示空间 */
:deep(.ant-modal-content) {
  max-height: 80vh !important;
}

/* 调整FormItem的间距和布局 */
:deep(.ant-form-item) {
  margin-bottom: 16px !important;
}

/* 选项卡内容区域 */
:deep(.ant-tabs-content-holder) {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  height: calc(80vh - 60px);
}

/* 表单内容区域 - 允许滚动 */
:deep(.ant-form) {
  max-height: 100%;
  overflow-y: auto;
  padding: 0;
}
</style>
